package com.zang.im.croom.netty.handler;

import com.zang.im.croom.model.dto.WSMessage;
import com.zang.im.croom.model.protobuf.WSMessageOuterClass;
import com.zang.im.croom.netty.common.SSGlobalConstMap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author Zhang Qiang
 * @Date 2019/7/27 18:22
 */
@Slf4j
public class WsProtoMsgHandler extends SimpleChannelInboundHandler<WSMessageOuterClass.WSMessage> {

    /**
     * 所有链接
     */
    private Map<String, Channel> channelMap = SSGlobalConstMap.getChannelMap();

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, WSMessageOuterClass.WSMessage wsMessage) throws Exception {

        Channel channel = ctx.channel();

    }

     /**
      * 发送消息
      */
    private void sendMsg( String key , WSMessage msg){

    }


    /**
     * 断开时删除
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelMap.entrySet().stream().filter(entry -> entry.getValue() == ctx.channel()).forEach(entry -> channelMap.remove(entry.getKey()));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        if("Connection reset by peer".equalsIgnoreCase(cause.getMessage())){
            log.error("连接被重置");
        }
        log.warn("连接出现问题");
    }


}
